package com.duleme.servlet;

import com.duleme.common.Config;
import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.UserDao;
import com.duleme.entity.User;
import com.duleme.entity.UserInfo;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@MultipartConfig
@WebServlet("/uploadAvatar")
public class AvatarServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //super.doPost(req, resp);
        EncodeUtils.setEncoding(request, response);
        //存储路径
        String savePath = Config.USER_AVATAR_SAVE_PATH;
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            //Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
            //Part part = parts[0];//从上传的文件集合中获取Part对象

            Part part = request.getPart("upload");//通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象

            //Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
            //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
            if (part != null) {
                String header = part.getHeader("content-disposition");
                //获取文件名
                int userId = user.getUserId();
                String fileName = String.valueOf(userId) + ".jpg";
                //把文件写到指定路径
                String accessPath = Config.USER_AVATAR_ACCESS_PATH + fileName;
                part.write(savePath + File.separator + fileName);

                if (new UserDao().updateAvatar(accessPath, userId)) {
                    user.setAvatar(accessPath);
                    //response.getWriter().print(JsonUtils.result2Json("1"));
                    request.getSession().setAttribute("user",user);
                    RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("/Self_Information.jsp");
                    requestDispatcher.forward(request,response);
                } else {
                    response.getWriter().println(JsonUtils.result2Json("0"));
                }
            } else
                response.getWriter().print(JsonUtils.result2Json("0"));
        } else {
            response.getWriter().print(JsonUtils.result2Json("0"));
        }


    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
